package com.free.bsf.elk;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;
import com.free.bsf.core.util.PropertyUtils;
import com.free.bsf.core.util.StringUtils;
import com.free.bsf.core.util.WarnUtils;
import lombok.val;

/**
 * @Classname LogWarnFilter
 * @Description 日志报警过滤器
 * @Date 2021/4/23 20:20
 * @Created by chejiangyi
 */
public class LogWarnFilter  extends AbstractMatcherFilter<ILoggingEvent> {
    @Override
    public FilterReply decide(ILoggingEvent event) {
        if(event.getLevel() == Level.ERROR) {
            if(PropertyUtils.getPropertyCache(ElkProperties.BsfElkWarnEnabled,false)) {
                try {
                    val message = event.getFormattedMessage();
                    if (message != null && (message.startsWith("【报警】")||message.startsWith("[报警]"))) {
                        WarnUtils.notify(WarnUtils.ALARM_ERROR,
                                "日志报警",
                                StringUtils.subString3(message, 100));
                    }
                }catch (Exception e){
                    //报警失败就放弃了,避免死循环
                }
            }
        }
        return FilterReply.NEUTRAL;
    }
}
